using System.Collections.Generic;
using ProtoModels;
using UnityEngine;

public class FriendsDisplay : MonoBehaviour
{
	public enum FriendDisplayAction
	{
		Invite = 0,
		SendGifts = 1,
		SendSocialRequest = 2
	}

	private interface FacebookFriendRequest
	{
		void GetFriendList(GGServerRequestsBackend.OnComplete onComplete);

		void SendFriendRequest(List<InvitableFriends.InvitableFriend> friends, GGMessageConfig.FbObjectType giftType);

		string GetDisplayHeaderText();

		string GetDisplayFooterText();
	}

	private class FacebookInviteFriends : FacebookFriendRequest
	{
		public void GetFriendList(GGServerRequestsBackend.OnComplete onComplete)
		{
			GGServerRequestsBackend.FacebookInviteFriends inviteRequest = new GGServerRequestsBackend.FacebookInviteFriends();
			BehaviourSingletonInit<GGServerRequestsBackend>.instance.GetFacebookInvites(inviteRequest, onComplete);
		}

		public void SendFriendRequest(List<InvitableFriends.InvitableFriend> friends, GGMessageConfig.FbObjectType giftType)
		{
			GGFacebook.FriendRequestData friendRequestData = default(GGFacebook.FriendRequestData);
			friendRequestData.message = "Invite friends to play!";
			friendRequestData.userIds = GetUserIds(friends);
			friendRequestData.actionType = string.Empty;
			friendRequestData.objectId = string.Empty;
			GGFacebook.FriendRequestData requestData = friendRequestData;
			GGFacebook.instance.OnClickRequestButton(requestData);
		}

		private string GetUserIds(List<InvitableFriends.InvitableFriend> friends)
		{
			string text = string.Empty;
			for (int i = 0; i < friends.Count; i++)
			{
				text = text + friends[i].id.ToString() + ((i >= friends.Count - 1) ? string.Empty : ",");
			}
			return text;
		}

		public string GetDisplayHeaderText()
		{
			return "Invite your friends to play!";
		}

		public string GetDisplayFooterText()
		{
			return " invites left";
		}
	}

	private class FacebookSendGift : FacebookFriendRequest
	{
		public void GetFriendList(GGServerRequestsBackend.OnComplete onComplete)
		{
			GGServerRequestsBackend.FacebookPlayingFriends playersRequest = new GGServerRequestsBackend.FacebookPlayingFriends();
			BehaviourSingletonInit<GGServerRequestsBackend>.instance.GetFacebookPlayers(playersRequest, onComplete);
		}

		public void SendFriendRequest(List<InvitableFriends.InvitableFriend> friends, GGMessageConfig.FbObjectType giftType)
		{
			GGMessageConfig.FacebookGiftObject giftForType = GGMessageConfig.instance.GetGiftForType(giftType);
			GGFacebook.FriendRequestData friendRequestData = default(GGFacebook.FriendRequestData);
			friendRequestData.message = giftForType.message;
			friendRequestData.userIds = GetUserIds(friends);
			friendRequestData.actionType = "send";
			friendRequestData.objectId = giftForType.objectId;
			GGFacebook.FriendRequestData requestData = friendRequestData;
			GGFacebook.instance.OnClickRequestButton(requestData);
		}

		private string GetUserIds(List<InvitableFriends.InvitableFriend> friends)
		{
			string text = string.Empty;
			for (int i = 0; i < friends.Count; i++)
			{
				text = text + friends[i].id.ToString() + ((i >= friends.Count - 1) ? string.Empty : ",");
			}
			return text;
		}

		public virtual string GetDisplayHeaderText()
		{
			return "Send gifts to your friends!";
		}

		public virtual string GetDisplayFooterText()
		{
			return " gifts left";
		}
	}

	private class FacebookSendSocialRequest : FacebookSendGift
	{
		public override string GetDisplayHeaderText()
		{
			return "Ask friends to hang out!";
		}

		public override string GetDisplayFooterText()
		{
			return " social invites left";
		}
	}

	public UIScrollView friendView;

	public UITable grid;

	public GameObject friendButtonPrefab;

	public GameObject loadingLayer;

	public UILabel header;

	public UILabel requestCount;

	public UILabel priceLabel;

	public GameObject priceDisplay;

	public UIWidget paddingButton;

	public int maxRequestCount = 10;

	public int maxFriendsToDisplay = 10;

	public UISprite submitButton;

	public string activeSubmitButtonSprite = "button-plastic";

	public string dissabledSubmitButtonSprite = "button-plastic-black";

	public UISprite selectAllButton;

	public UILabel selectAllLabel;

	private bool shouldSelectAll = true;

	public UIWidget scrollPadding;

	private List<FriendsButton> friendButtons = new List<FriendsButton>();

	private bool hasBeenAligned;

	private bool finishedInit;

	private FriendDisplayAction currentAction;

	private GGMessageConfig.FbObjectType giftType = GGMessageConfig.FbObjectType.None;

	private int fetchFriendPicturesRequestTicket = -1;

	private int outstandingTextureRequests;

	private FacebookFriendRequest friendRequestHandler;

	private InvitableFriends myFriends;

	private static FacebookFriendRequest GetFacebookRequestImplementation(FriendDisplayAction action)
	{
		switch (action)
		{
		case FriendDisplayAction.SendGifts:
			return new FacebookSendGift();
		case FriendDisplayAction.Invite:
			return new FacebookInviteFriends();
		case FriendDisplayAction.SendSocialRequest:
			return new FacebookSendSocialRequest();
		default:
			return null;
		}
	}

	public void Init(FriendDisplayAction action, GGMessageConfig.FbObjectType giftType)
	{
		currentAction = action;
		this.giftType = giftType;
	}

	private void OnEnable()
	{
		hasBeenAligned = false;
		shouldSelectAll = true;
		GetFriendsToDisplay();
	}

	private void GetFriendsToDisplay()
	{
		finishedInit = false;
		friendRequestHandler = GetFacebookRequestImplementation(currentAction);
		InitialiseDisplayForFriendQuery();
		friendRequestHandler.GetFriendList(FriendListRequestComplete);
	}

	private void InitialiseDisplayForFriendQuery()
	{
		UITools.ChangeText(header, (friendRequestHandler == null) ? string.Empty : friendRequestHandler.GetDisplayHeaderText());
		string text = Mathf.Min(maxRequestCount, maxFriendsToDisplay).ToString();
		UITools.ChangeText(requestCount, (friendRequestHandler == null) ? string.Empty : (text + friendRequestHandler.GetDisplayFooterText()));
		GGMessageConfig.FacebookGiftObject giftForType = GGMessageConfig.instance.GetGiftForType(giftType);
		UITools.ChangeText(priceLabel, GGFormat.FormatPrice((giftForType != null) ? giftForType.coinCost : 0));
		priceDisplay.SetActive(giftForType != null && giftForType.coinCost > 0);
		loadingLayer.SetActive(true);
	}

	private void OnDisable()
	{
		paddingButton.gameObject.SetActive(false);
		HideUnusedButtons(0);
		if (fetchFriendPicturesRequestTicket >= 0 && BehaviourSingleton<GGRequestLimitter>.instance != null)
		{
			BehaviourSingleton<GGRequestLimitter>.instance.StopRequestsWithGroup(fetchFriendPicturesRequestTicket);
		}
	}

	private void OnCantReachServerDialogDone(bool success)
	{
		GGPlayerSettings.instance.Model.hasLoggedIntoFacebook = false;
		GGPlayerSettings.instance.Save();
		BehaviourSingletonInit<FriendProfilesManager>.instance.RefreshFriendProfiles();
		NavigationManager.instance.Pop();
		NavigationManager.instance.Pop();
		NavigationManager.instance.ReloadActiveLayer();
	}

	public void FriendListRequestComplete(GGServerRequestsBackend.ServerRequest request)
	{
		loadingLayer.SetActive(false);
		shouldSelectAll = true;
		if (request.status != 0)
		{
			if (!GGSupportMenu.instance.isNetworkConnected())
			{
				TableTennisDialog.instance.ShowOk("No Internet Connection", "No internet connection! Please connect to internet and try again.", "Ok", OnCantReachServerDialogDone);
			}
			else if (request.errorMessage == ConfigBase.instance.facebookError)
			{
				TableTennisDialog.instance.ShowOk("Facebook request not available", "Facebook friend list get request failed! Try re-signing into facebook.", "Ok", OnCantReachServerDialogDone);
			}
		}
		else
		{
			myFriends = request.GetResponse<InvitableFriends>();
			InitialiseFriendsDisplay(myFriends);
		}
	}

	private void InitialiseFriendsDisplay(InvitableFriends friends)
	{
		int friendsToDisplay = Mathf.Min(maxFriendsToDisplay, friends.data.Count);
		InitialiseButtons(friendsToDisplay, friends);
		HideUnusedButtons(friendsToDisplay);
		grid.Reposition();
		hasBeenAligned = false;
		finishedInit = true;
	}

	private void InitialiseButtons(int friendsToDisplay, InvitableFriends friends)
	{
		Debug.Log("# of friends received: " + friends.data.Count);
		paddingButton.gameObject.SetActive(friends.data.Count % 2 != 0);
		fetchFriendPicturesRequestTicket = BehaviourSingleton<GGRequestLimitter>.instance.GetGroupId();
		outstandingTextureRequests = 0;
		for (int i = 0; i < friendsToDisplay; i++)
		{
			InvitableFriends.InvitableFriend friend = friends.data[i];
			if (i >= friendButtons.Count)
			{
				paddingButton.name = GGFormat.IndexName(i + 1);
				AddNewFriendButton(GGFormat.IndexName(i));
			}
			friendButtons[i].gameObject.SetActive(true);
			friendButtons[i].Init(friend, fetchFriendPicturesRequestTicket, this);
			outstandingTextureRequests++;
		}
		UIPanel component = friendView.GetComponent<UIPanel>();
		scrollPadding.transform.localPosition = Vector3.zero;
		scrollPadding.width = (int)component.width;
		scrollPadding.height = (int)Mathf.Max(grid.transform.localScale.y * (float)friendsToDisplay * ((float)friendButtonPrefab.GetComponent<UIWidget>().height + grid.padding.y), component.height);
	}

	private void AddNewFriendButton(string name)
	{
		GameObject gameObject = NGUITools.AddChild(grid.gameObject, friendButtonPrefab);
		gameObject.name = name;
		FriendsButton component = gameObject.GetComponent<FriendsButton>();
		friendButtons.Add(component);
	}

	public void OnTextureArrived()
	{
		outstandingTextureRequests--;
		if (outstandingTextureRequests <= 0)
		{
			outstandingTextureRequests = 0;
			fetchFriendPicturesRequestTicket = -1;
		}
	}

	private void HideUnusedButtons(int friendsToDisplay)
	{
		for (int i = friendsToDisplay; i < friendButtons.Count; i++)
		{
			friendButtons[i].gameObject.SetActive(false);
			friendButtons[i].toggle.value = false;
		}
	}

	public void SendInvites()
	{
		if (GetSelectedFriendsCount() == 0)
		{
			TableTennisDialog.instance.ShowOk("You have to select friends first", "You have to select some friends first! You can select friends by clicking on them in the list.", "Ok", null);
			return;
		}
		GGMessageConfig.FacebookGiftObject giftForType = GGMessageConfig.instance.GetGiftForType(giftType);
		if (giftForType != null && giftForType.coinCost > GGPlayerSettings.instance.Model.coins)
		{
			TableTennisDialog.instance.ShowOk("Not Enough Coins", "Sorry, you don't have enough coins.", "ok", null);
			return;
		}
		SendRequests();
		NavigationManager.instance.Pop();
	}

	public void SelectAll()
	{
		int num = Mathf.Min(maxFriendsToDisplay, myFriends.data.Count);
		for (int i = 0; i < num; i++)
		{
			friendButtons[i].toggle.value = shouldSelectAll;
		}
		shouldSelectAll = !shouldSelectAll;
	}

	public void OnSendRequestSuccess(string success)
	{
		Debug.Log("fb dialog success");
		GGMessageConfig.FacebookGiftObject giftForType = GGMessageConfig.instance.GetGiftForType(giftType);
		WalletManager walletManager = GGPlayerSettings.instance.walletManager;
		walletManager.BuyItemCoins(giftForType.coinCost);
		UpdatePopularity();
		UpdateMood();
		GGPlayerSettings instance = GGPlayerSettings.instance;
		LevelUpLayer.LevelProgressInfo levelProgressInfo = default(LevelUpLayer.LevelProgressInfo);
		levelProgressInfo.levelProgress = instance.LevelProgress();
		levelProgressInfo.levelName = instance.LevelName();
		LevelUpLayer.LevelProgressInfo oldLevel = levelProgressInfo;
		levelProgressInfo = default(LevelUpLayer.LevelProgressInfo);
		levelProgressInfo.levelProgress = instance.LevelProgress();
		levelProgressInfo.levelName = instance.LevelName();
		LevelUpLayer.LevelProgressInfo newLevel = levelProgressInfo;
		LevelUpLayer.instance.DoShowLevelProgress(oldLevel, newLevel);
	}

	private void UpdatePopularity()
	{
		PlayerStats playerStats = GGPlayerSettings.instance.statsManager.playerStats;
		GGMessageConfig.FacebookGiftObject giftForType = GGMessageConfig.instance.GetGiftForType(giftType);
		playerStats.UpdateAttribute(giftForType.popularityBoost, 3);
	}

	private void UpdateMood()
	{
		PlayerMood playerMood = GGPlayerSettings.instance.statsManager.playerMood;
		GGMessageConfig.FacebookGiftObject giftForType = GGMessageConfig.instance.GetGiftForType(giftType);
		playerMood.UpdateMood(giftForType.moodBoost);
	}

	private void SendRequests()
	{
		List<InvitableFriends.InvitableFriend> selectedFriends = GetSelectedFriends();
		friendRequestHandler.SendFriendRequest(selectedFriends, giftType);
		Analytics.instance.FacebookFriendRequestSent(selectedFriends.Count);
	}

	public int GetSelectedFriendsCount()
	{
		int num = 0;
		foreach (FriendsButton friendButton in friendButtons)
		{
			if (friendButton.IsToggleOn())
			{
				num++;
			}
		}
		return num;
	}

	private List<InvitableFriends.InvitableFriend> GetSelectedFriends()
	{
		List<InvitableFriends.InvitableFriend> list = new List<InvitableFriends.InvitableFriend>();
		foreach (FriendsButton friendButton in friendButtons)
		{
			if (friendButton.IsToggleOn())
			{
				list.Add(friendButton.friend);
			}
		}
		return list;
	}

	private void Update()
	{
		submitButton.spriteName = ((GetSelectedFriendsCount() != 0) ? activeSubmitButtonSprite : dissabledSubmitButtonSprite);
		selectAllButton.spriteName = ((friendButtons.Count != 0) ? activeSubmitButtonSprite : dissabledSubmitButtonSprite);
		UITools.ChangeText(selectAllLabel, (!shouldSelectAll) ? "Uncheck all" : "Check all");
		if (!hasBeenAligned && finishedInit)
		{
			grid.Reposition();
			if (friendButtons.Count > 0)
			{
				UITools.AlignToTopOnScroll(friendButtons[0].gameObject.GetComponent<UIWidget>(), friendView, 0f);
			}
			hasBeenAligned = true;
		}
		if (friendButtons.Count <= 0 || loadingLayer.activeSelf)
		{
			return;
		}
		UIPanel component = friendView.GetComponent<UIPanel>();
		foreach (FriendsButton friendButton in friendButtons)
		{
			friendButton.gameObject.SetActive(false);
			friendButton.gameObject.SetActive(component.IsVisible(friendButton.GetComponent<UIWidget>()));
		}
	}
}
